package edu.friday.controller;

import edu.friday.common.base.BaseController;
import edu.friday.common.constant.UserConstants;
import edu.friday.common.result.RestResult;
import edu.friday.common.result.TableDataInfo;
import edu.friday.model.SysRoleEntity;
import edu.friday.model.vo.SysRoleVo;
import edu.friday.service.SysMenuService;
import edu.friday.service.SysRoleService;
import edu.friday.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController {

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysMenuService menuService;

    @GetMapping("/list")
    public TableDataInfo list(SysRoleEntity user, Pageable page) {
        int pageNum = page.getPageNumber() - 1;
        pageNum = Math.max(pageNum, 0);
        page = PageRequest.of(pageNum, page.getPageSize());
        return roleService.selectRoleList(user, page);
    }

    @PostMapping
    public RestResult add(@RequestBody SysRoleVo roleVo) {
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(roleVo.getRoleName()))) {
            return RestResult.error("新增用户" + roleVo.getRoleName() + "失败 该角色已存在");
        }
        roleVo.setCreateBy("system");
        boolean flag = roleService.insertRole(roleVo);
        return toAjax(flag ? 1 : 0);
    }

    @GetMapping(value = {"/", "{roleId}"})
    public RestResult getInfo(@PathVariable(value = "roleId", required = false) Long roleId) {
        RestResult ajax = RestResult.success();
        ajax.put("menus", menuService.selectMenuAll());
        if (StringUtils.isNotNull(roleId)) {
            ajax.put(RestResult.DATA_TAG, roleService.selectRoleById(roleId));
            ajax.put("menuIds", menuService.selectMenuListByRoleId(roleId));
        }
        return ajax;
    }

    @PutMapping("/changeStatus")
    public RestResult edit(@Validated @RequestBody SysRoleVo roleVo) {
        boolean flag = roleService.updateRole(roleVo);
        return toAjax(flag ? 1 : 0);
    }
}
